﻿using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net.Mail;
using SolidDemo.Business.Interfaces;

namespace SolidDemo.Business.Helpers
{
    public class MessageHelper : IMessageHelper
    {
        public void SendEmail(string fromAddress, string toAddress, string subject, string message, bool isHtml = false, List<MemoryStream> attachments = null, List<string> attachmentFilenames = null)
        {
            if (toAddress.ToLower().Contains("@test.com")) toAddress = "ritsurinkoen@gmail.com";

            var mail = new MailMessage(fromAddress, toAddress);
            var client = new SmtpClient();

            mail.Subject = subject;
            mail.Body = message;
            mail.IsBodyHtml = isHtml;

            if (attachments != null && attachmentFilenames != null)
            {
                for (var i = 0; i < attachments.Count; i++)
                {
                    var ms = new MemoryStream(attachments[i].ToArray());
                    var filename = attachmentFilenames[i];
                    var attachment = new Attachment(ms, filename);
                    mail.Attachments.Add(attachment);
                }
            }

            client.Send(mail);
        }

        public void SendEmailFromSystem(string toAddress, string subject, string message, bool isHtml = false, List<MemoryStream> attachments = null, List<string> attachmentFilenames = null)
        {
            var fromAddress = ConfigurationManager.AppSettings["systemFromAddress"];

            SendEmail(fromAddress, toAddress, subject, message, isHtml, attachments, attachmentFilenames);
        }

        public void SendErrorEmail(string message, string priority)
        {
            var errorToAddress = ConfigurationManager.AppSettings["errorToAddress"];
            var subject = string.Format("CapSub Error - {0}", priority);

            SendEmailFromSystem(errorToAddress, subject, message);
        }
    }
}
